package org.jeecg.modules.school.consult.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.school.consult.entity.MemSchoolSeekHelp;
import org.jeecg.modules.school.consult.service.MemSchoolHelpService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description: 求助咨询
 * @author: kalman
 * @date: 2022-01-17- 14:46
 */
@Slf4j
@RestController
@RequestMapping("/school/consult/seek")
public class SeekHelpController {

    @Autowired
    private MemSchoolHelpService helpService;

    @Resource
    private BaseCommonService baseCommonService;

    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public Result<IPage<MemSchoolSeekHelp>> queryPage
            (MemSchoolSeekHelp seekHelp, @RequestParam(name = "pageNo",defaultValue = "1")Integer pageNo,
             @RequestParam(name = "pageSize",defaultValue = "10")Integer pageSize, HttpServletRequest request
            ){
        //
        Result<IPage<MemSchoolSeekHelp>> result = new Result<IPage<MemSchoolSeekHelp>>();
        QueryWrapper<MemSchoolSeekHelp> queryWrapper=
                QueryGenerator.initQueryWrapper(seekHelp, request.getParameterMap());

        Page<MemSchoolSeekHelp> page=new Page<>(pageNo,pageSize);
        Page<MemSchoolSeekHelp> pageList = helpService.page(page,queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        log.info("查詢的求助咨詢列表目錄為==>"+pageList.getRecords());

        return result;
    }

    /**
     * 編輯求助咨詢表
     * @param jsonObject
     * @param request
     * @return
     */
    @PutMapping("/edit")
    public Object edit(@RequestBody JSONObject jsonObject, HttpServletRequest request){
        log.info("進來了===》 edit ==>"+jsonObject);
        Result<Object> result=new Result<>();
        try{
            MemSchoolSeekHelp help=helpService.getById(jsonObject.getString("id"));
            baseCommonService.addLog("編輯，id： " +jsonObject.getString("id") , CommonConstant.LOG_TYPE_2, 2);
            if(help==null){
                result.error500("未找到實體");
            }else {
                MemSchoolSeekHelp seekHelp=JSONObject.parseObject(jsonObject.toJSONString(),MemSchoolSeekHelp.class);
                System.out.println(seekHelp.getIssueType());
                seekHelp.setCreateTime(help.getCreateTime());
                seekHelp.setUpdaterId(((LoginUser)SecurityUtils.getSubject().getPrincipal()).getRealname());
                seekHelp.setUpdateTime(new Date());
                helpService.updateById(seekHelp);
                result.setMessage("修改成功");
            }
        }catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        result.setSuccess(true);
        return result;
    }


    /**
     * 添加求助咨詢表
     * @param jsonObject
     * @return
     */

    @RequestMapping(value = "/add",method = {RequestMethod.POST,RequestMethod.PUT})
    public Object add(@RequestBody JSONObject jsonObject){
        log.info("進來了===》 add  ==>"+jsonObject);
        Result<Object> result=new Result<>();
        try{
            MemSchoolSeekHelp seekHelp=JSONObject.parseObject(jsonObject.toJSONString(),MemSchoolSeekHelp.class);
            System.out.println(seekHelp.getIssueType());
            seekHelp.setCreatorId(((LoginUser)SecurityUtils.getSubject().getPrincipal()).getRealname());
            seekHelp.setCreateTime(new Date());
            seekHelp.setConsultationNo(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            helpService.save(seekHelp);
            result.setMessage("添加成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }

        result.setSuccess(true);
        return result;
    }

    /**
     * 刪除求助咨詢表
     * 其實是將 dr 更新為 1
     */

    @RequestMapping(value = "/delete",method = RequestMethod.DELETE)
    public  Object delete(@RequestParam(name="id",required=true) String id){
        log.info("需要刪除的 id 為 ===》"+id);
        //選擇性更新
        this.helpService.deleteSeekById(id);
        baseCommonService.addLog("刪除求助咨詢表，id： " +id ,CommonConstant.LOG_TYPE_2, 3);
        return Result.ok("刪除成功");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @RequestMapping(value = "/deleteBatch",method = RequestMethod.DELETE)
    public  Object deleteBatch(@RequestParam(name="ids",required=true) String ids){
        log.info("需要刪除的 id 為 ===》"+ids);
        //選擇性更新
        this.helpService.deleteBatchSeekById(ids);
        baseCommonService.addLog("批量刪除求助咨詢表，id： " +ids,CommonConstant.LOG_TYPE_2, 3);
        return Result.ok("刪除成功");
    }

    /**
     * 查詢 dr = 1 的咨詢表
     * 回收站
     */
//    @RequestMapping(value = "/recycleBin",method = RequestMethod.GET)
//    public  Object recycleBin(){
//        log.info("查詢回收站");
//
//        QueryWrapper<MemSchoolSeekHelp> queryWrapper=new QueryWrapper<>();
//        queryWrapper.eq("dr",1);
//        List<MemSchoolSeekHelp> list = this.helpService.list(queryWrapper);
//
//
//
//        return Result.ok(list);
//    }

//    @RequestMapping(value = "/putRecycleBin" ,method = RequestMethod.PUT)
//    public Object putRecycleBin(@RequestBody JSONObject jsonObject,HttpServletRequest request){
//        log.info("需要還原的 咨詢表為===》"+jsonObject.getString("seekIds"));
//
//        this.helpService.refreshDrBatchById(jsonObject.getString("seekIds"));
//        return Result.ok("還原成功");
//    }

    @RequestMapping(value = "/exportXls")
    public Object exportXls(MemSchoolSeekHelp memSchoolSeekHelp,HttpServletRequest request){
        // Step.1 组装查询条件
        QueryWrapper<MemSchoolSeekHelp> queryWrapper =
                QueryGenerator.initQueryWrapper(memSchoolSeekHelp, request.getParameterMap());
        //
        ModelAndView mv=new ModelAndView(new JeecgEntityExcelView());
        //update-begin--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据--------------------
        String selections = request.getParameter("selections");
        if(!oConvertUtils.isEmpty(selections)){
            queryWrapper.in("id",selections.split(","));
        }
        List<MemSchoolSeekHelp> pageList = this.helpService.list(queryWrapper);
        mv.addObject(NormalExcelConstants.FILE_NAME,"咨詢列表");
        mv.addObject(NormalExcelConstants.CLASS,MemSchoolSeekHelp.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();//TODO
        log.info("導出人：=》"+user);
        String tempRealname;
        if (user==null){
            tempRealname="未知";
        }else {
            tempRealname=user.getRealname();
        }
        ExportParams exportParams = new ExportParams("咨詢列表數據", "導出人："+tempRealname, "導出信息");
        exportParams.setImageBasePath(upLoadPath);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        log.info("===========導出結束========================");
        return mv;
    }




}
